// pages/assemble_detail/assemble_detail.js
var common = require("../../common/common.js").common;

var leader = require("../../common/leader.js").leader;

var WxParse = require("../../wxParse/wxParse.js");

var util = require("../../utils/util.js");

const app = getApp();

var {$author: $author} = require("../../components/base/authorization.js");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        carousel_img: [ "/images/luck_discount.jpg", "/images/luck_discount.jpg", "/images/luck_discount.jpg" ],
        currentSwiper: 0,
        details: "",
        //商品详情
        pro_id: "",
        //商品id
        detail: "",
        //商品详情介绍
        buy_count: 1,
        //购买数量
        sku: "",
        sku_info: "",
        alert: 0,
        //规格弹窗
        skubox: "",
        ladder: 0,
        //阶梯团弹窗
        ladder_person: [],
        //阶梯团
        choose_ladder: 0,
        //选择阶梯团
        ladder_low_price: 0,
        //阶梯团最低价
        ladder_id: "",
        //阶梯团id
        spelling: 0,
        //拼单用户弹窗
        spellingData: [],
        //拼单用户数据
        spellingUser: 0,
        //参与拼单用户弹窗
        userData: [],
        //参与拼单用户信息
        type: 0,
        //购买方式
        proceed_id: "",
        rows: [],
        //详情正在拼单
        time: "",
        //参与别人拼单倒计时
        on_off_trans_free: 0,
        trans_for_free_barrier: 0,
        timer: "",
        tmplIds: [],
        subscribeMessage: true
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        wx.showShareMenu({
            // withShareTicket: true,
            menus: [ "shareAppMessage", "shareTimeline" ]
        });
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        let that = this;
        let pro_id = options.id;
        const system = wx.getSystemInfoSync().system;
        const isIOS = system.includes("iOS");
        this.setData({
            isIOS: isIOS
        });
        that.setData({
            pro_id: pro_id
        });
        leader.getMyLeaderInfo();
        //公用方法团长请求
                that.getDetails();
        that.getBase();
        that.getTmplIds();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {
        let that = this;
        return {
            title: that.data.details.name,
            imageUrl: that.data.details.icon,
            path: "/pages/assemble_detail/assemble_detail?id=" + that.data.pro_id
        };
    },
    onShareTimeline: function() {
        let that = this;
        return {
            title: that.data.details.name,
            imageUrl: that.data.details.icon,
            // 图片 URL
            query: "id=" + that.data.pro_id
        };
    },
    //轮播图
    swiperChange: function(e) {
        this.setData({
            currentSwiper: e.detail.current
        });
    },
    //获取商品详情
    getDetails: function() {
        let that = this;
        let pro_id = that.data.pro_id;
        common.request({
            endpoint: "Groupbuy/product/info",
            method: "post",
            data: {
                id: pro_id
            },
            header: {},
            success: function(res) {
                let details = res.extra;
                details.sku_attribute = details.sku_attribute.map(item => {
                    item.attribute_value = that.selectSingleSku(item.attribute_value);
                    return item;
                });
                let sku_attribute = details.sku_attribute;
                let sku = sku_attribute.reduce((s, v) => {
                    s = that.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                    return s;
                }, "");
                let sku_info = that.getProductBySku(details.sku, sku);
                that.setData({
                    sku_info: sku_info,
                    details: details,
                    detail: WxParse.wxParse("detail", "html", details.detail, that, 0),
                    sku: sku,
                    skubox: details,
                    rebate: res.extra.rebate
                });
                that.spellTime();
            },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: err.message,
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            wx.navigateBack({
                                delta: 0
                            });
                        }
                    }
                });
            }
        });
    },
    /** 
   * 添加 sku 属性
   */
    addSkuAttribute: function(e) {
        let key_id = parseInt(e.currentTarget.dataset.key_id);
        let value_id = parseInt(e.currentTarget.dataset.value_id);
        let a_key_index = parseInt(e.currentTarget.dataset.a_key_index);
        let a_value_index = parseInt(e.currentTarget.dataset.a_value_index);
        let sku = this.data.sku;
        sku = this.reBlanceSku(sku, key_id, value_id);
        let attribute = this.data.skubox.sku_attribute;
        attribute = this.selectSku(attribute, a_key_index, a_value_index);
        let sku_info = this.getProductBySku(this.data.skubox.sku, sku);
        this.setData({
            sku: sku,
            ["details.sku_attribute"]: attribute,
            sku_info: sku_info
        });
    },
    /** 
   * 重平衡 sku
   * key_id: integer
   */
    reBlanceSku: function(sku, key_id, value_id) {
        let sku_lib = sku != "" ? this.splitSku(sku) : [];
        sku_lib = this.addSku(sku_lib, {
            key_id: key_id,
            value_id: value_id
        });
        sku_lib = this.sortSku(sku_lib);
        return this.buildSku(sku_lib);
    },
    /** 
   * 重建 sku
   */
    buildSku: function(sku_lib) {
        return sku_lib.map(item => {
            return item.key_id + "," + item.value_id;
        }).join("|");
    },
    /** 
   * 对选择的 sku 属性进行排序
   */
    sortSku: function(sku_lib) {
        return sku_lib.sort((pre, next) => {
            if (pre.key_id > next.key_id) {
                return 1;
            } else if (pre.key_id < next.key_id) {
                return -1;
            } else {
                return 0;
            }
        });
    },
    /** 
   * 分割现有 sku 成对象数组
   */
    splitSku: function(sku) {
        return sku.split("|").map(sku_tmp => {
            let [key, value] = sku_tmp.split(",");
            const t = {};
            t.key_id = parseInt(key);
            t.value_id = parseInt(value);
            return t;
        });
    },
    /** 
   * 添加一个 sku
   */
    addSku: function(sku_lib, sku) {
        let t = sku_lib.filter(item => {
            if (item.key_id === sku.key_id) {
                return false;
            }
            return true;
        });
        t.push(sku);
        return t;
    },
    /** 
   * 选择 sku
   */
    selectSku: function(attribues, a_index, v_index = 0) {
        if (attribues[a_index]) {
            let values = attribues[a_index].attribute_value;
            values = values.map(item => {
                item.selected = false;
                return item;
            });
            values[v_index].selected = true;
            attribues[a_index].attribute_value = values;
        }
        return attribues;
    },
    /** 
   * 选择单个 sku 属性
   */
    selectSingleSku: function(attribute_value, v_index = 0) {
        attribute_value.map(item => {
            item.selected = false;
            return item;
        });
        attribute_value[v_index].selected = true;
        return attribute_value;
    },
    /**
   * 根据 sku 获取物品
   */
    getProductBySku: function(sku_products, sku) {
        return sku_products[sku];
    },
    save_count: function(e) {
        this.setData({
            buy_count: parseInt(e.detail.value)
        });
    },
    blur: function(e) {
        let count = e.detail.value;
        if (count <= 0) {
            count = 1;
        }
        this.setData({
            buy_count: parseInt(count)
        });
    },
    reduce_count: function() {
        let buy_count = this.data.buy_count;
        if (buy_count > 1) {
            buy_count--;
        }
        this.setData({
            buy_count: buy_count
        });
    },
    add_count: function(e) {
        let that = this;
        that.add_count_ch(e);
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {}
            });
        }
    },
    add_count_ch: function(e) {
        let buy_count = this.data.buy_count;
        let restrictions = e.currentTarget.dataset.restrictions;
        let pro_limit = this.data.sku_info.pro_limit;
        if (pro_limit == 0) {
            buy_count++;
        } else {
            if (buy_count >= pro_limit) {
                wx.showModal({
                    title: "提示",
                    content: "本商品限购" + pro_limit + "份"
                });
            } else {
                buy_count++;
            }
        }
        this.setData({
            buy_count: buy_count
        });
    },
    alone_buy: function() {
        let that = this;
        common.getUserInfoNew({
            success() {
                that.alone_buy_ch();
                if (that.data.subscribeMessage) {
                    wx.requestSubscribeMessage({
                        tmplIds: that.data.tmplIds,
                        success(res) {},
                        fail(err) {}
                    });
                } else {
                    that.alone_buy_ch();
                }
            }
        });
    },
    //单独购买
    alone_buy_ch: function() {
        let that = this;
        common.getUserInfoNew({
            success() {
                that.getDetails();
                that.setData({
                    alert: 1,
                    type: 0,
                    proceed_id: ""
                });
            }
        });
    },
    //关闭规格弹窗
    close_alert: function(e) {
        let that = this;
        that.setData({
            alert: 0
        });
    },
    //拼团购买
    spell_buy: function() {
        let that = this;
        let pro_id = that.data.pro_id;
        common.getUserInfoNew({
            success() {
                common.request({
                    endpoint: "Groupbuy/product/price_list",
                    method: "post",
                    data: {
                        id: pro_id
                    },
                    header: {},
                    success: function(res) {
                        let details = res.extra;
                        details.sku_attribute = details.sku_attribute.map(item => {
                            item.attribute_value = that.selectSingleSku(item.attribute_value);
                            return item;
                        });
                        let attribute = details.sku_attribute;
                        let sku_attribute = details.sku_attribute;
                        let sku = sku_attribute.reduce((s, v) => {
                            s = that.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                            return s;
                        }, "");
                        let sku_info = that.getProductBySku(details.sku, sku);
                        that.setData({
                            sku_info: sku_info,
                            sku: sku,
                            skubox: details,
                            alert: 1,
                            type: 1,
                            proceed_id: "",
                            ["details.sku_attribute"]: attribute
                        });
                    }
                });
            }
        });
    },
    ladder_buy: function() {
        let that = this;
        common.getUserInfoNew({
            success() {
                that.ladder_buy_ch();
                if (that.data.subscribeMessage) {
                    wx.requestSubscribeMessage({
                        tmplIds: that.data.tmplIds,
                        success(res) {},
                        fail(err) {}
                    });
                }
            }
        });
    },
    //阶梯团
    ladder_buy_ch: function() {
        let that = this;
        let pro_id = that.data.pro_id;
        common.getUserInfoNew({
            success() {
                common.request({
                    endpoint: "Groupbuy/product/price_list",
                    method: "post",
                    data: {
                        id: pro_id
                    },
                    header: {},
                    success: function(res) {
                        that.setData({
                            ladder: 1,
                            ladder_person: res.extra,
                            choose_ladder: res.extra[0].id,
                            type: 1,
                            proceed_id: res.extra[0].id,
                            ladder_low_price: res.extra[0].low_price
                        });
                    }
                });
            }
        });
    },
    //选择阶梯团
    choose_ladder: function(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;
        let low_price = e.currentTarget.dataset.price;
        that.setData({
            choose_ladder: id,
            proceed_id: id,
            ladder_low_price: low_price
        });
    },
    ladder_confirm: function() {
        let that = this;
        let pro_id = that.data.pro_id;
        let ladder_id = that.data.choose_ladder;
        common.request({
            endpoint: "Groupbuy/product/price_list",
            method: "post",
            data: {
                id: pro_id,
                group_id: ladder_id
            },
            header: {},
            success: function(res) {
                let details = res.extra;
                details.sku_attribute = details.sku_attribute.map(item => {
                    item.attribute_value = that.selectSingleSku(item.attribute_value);
                    return item;
                });
                let sku_attribute = details.sku_attribute;
                let attribute = details.sku_attribute;
                let sku = sku_attribute.reduce((s, v) => {
                    s = that.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                    return s;
                }, "");
                let sku_info = that.getProductBySku(details.sku, sku);
                that.setData({
                    sku_info: sku_info,
                    sku: sku,
                    skubox: details,
                    alert: 1,
                    ladder: 0,
                    ["details.sku_attribute"]: attribute
                });
            }
        });
    },
    //获取更多正在拼单用户
    getSpelling: function() {
        let that = this;
        let pro_id = that.data.pro_id;
        common.getUserInfoNew({
            success() {
                common.request({
                    endpoint: "Groupbuy/product/group_runing",
                    method: "post",
                    data: {
                        id: pro_id,
                        page: 1,
                        rows: 100
                    },
                    header: {},
                    success: function(res) {
                        that.setData({
                            spelling: 1,
                            spellingData: res.extra.rows
                        });
                        that.spellTime2();
                    }
                });
            }
        });
    },
    //关闭更多正在拼单
    close_spelling: function() {
        let that = this;
        that.setData({
            spelling: 0
        });
    },
    //参与拼单
    joinSpell: function() {
        let that = this;
        let pro_id = that.data.pro_id;
        let proceed_id = that.data.proceed_id;
        common.request({
            endpoint: "Groupbuy/product/price_list",
            method: "post",
            data: {
                id: pro_id,
                proceed_id: proceed_id
            },
            header: {},
            success: function(res) {
                let details = res.extra;
                details.sku_attribute = details.sku_attribute.map(item => {
                    item.attribute_value = that.selectSingleSku(item.attribute_value);
                    return item;
                });
                let sku_attribute = details.sku_attribute;
                let attribute = details.sku_attribute;
                let sku = sku_attribute.reduce((s, v) => {
                    s = that.reBlanceSku(s, parseInt(v.attribute_key.id), parseInt(v.attribute_value[0].id));
                    return s;
                }, "");
                let sku_info = that.getProductBySku(details.sku, sku);
                that.setData({
                    sku_info: sku_info,
                    sku: sku,
                    skubox: details,
                    alert: 1,
                    spellingUser: 0,
                    ["details.sku_attribute"]: attribute
                });
            },
            fail: function(res) {
                wx.showModal({
                    title: "提示",
                    content: res.message
                });
            }
        });
    },
    //参与正在拼单用户拼团
    getSpellinguser: function(e) {
        let that = this;
        let proceed_id = e.currentTarget.dataset.id;
        common.getUserInfoNew({
            success() {
                common.request({
                    endpoint: "Groupbuy/product/group_info",
                    method: "post",
                    data: {
                        proceed_id: proceed_id
                    },
                    header: {},
                    success: function(res) {
                        that.setData({
                            userData: res.extra,
                            spellingUser: 1,
                            proceed_id: proceed_id,
                            type: 2,
                            spelling: 0
                        });
                        that.count_down();
                    },
                    fail: function(res) {
                        wx.showModal({
                            title: "提示",
                            content: res.message
                        });
                    }
                });
            }
        });
    },
    //关闭正在拼单用户弹窗
    close_spellUser: function() {
        let that = this;
        clearInterval(that.data.timer);
        that.setData({
            spellingUser: 0,
            time: ""
        });
    },
    //确定购买
    confirm: function() {
        let that = this;
        let type = that.data.type;
        let sku_info = that.data.sku_info;
        let buy_count = that.data.buy_count;
        let proceed_id = that.data.proceed_id;
        let pro_limit = that.data.sku_info.pro_limit;
        if (pro_limit != 0 && buy_count > pro_limit) {
            wx.showModal({
                title: "提示",
                content: "本商品限购" + pro_limit + "份"
            });
            return false;
        }
        if (sku_info.stock_number >= buy_count) {
            var sku_item = sku_info.item_id + "," + buy_count;
            wx.navigateTo({
                url: `/newPlace_order/pages/newPlace_order/newPlace_order?operation=3&&sku_item=${sku_item}&&operation_type=${type}&&proceed_id=${proceed_id}`
            });
        } else {
            wx.showModal({
                title: "提示",
                content: "库存不足！"
            });
        }
    },
    //详情倒计时1
    spellTime: function() {
        let that = this;
        let dates = that.data.details.active.rows;
        let len = dates.length;
        //时间数据长度
                function nowTime() {
            //时间函数
            for (var i = 0; i < len; i++) {
                var intDiff = dates[i].rest_time;
                //获取数据中的时间戳
                                var day = 0, hour = 0, minute = 0, second = 0;
                if (intDiff > 0) {
                    //转换时间
                    day = Math.floor(intDiff / (60 * 60 * 24));
                    hour = Math.floor(intDiff / (60 * 60)) - day * 24;
                    minute = Math.floor(intDiff / 60) - day * 24 * 60 - hour * 60;
                    second = Math.floor(intDiff) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60;
                    if (hour <= 9) hour = "0" + hour;
                    if (minute <= 9) minute = "0" + minute;
                    if (second <= 9) second = "0" + second;
                    dates[i].rest_time--;
                    var str = hour + ":" + minute + ":" + second;
                } else {
                    var str = "已结束！";
                }
                dates[i].difftime = str;
                //在数据中添加difftime参数名，把时间放进去
                        }
            that.setData({
                rows: dates
            });
        }
        nowTime();
        var timer = setInterval(nowTime, 1e3);
    },
    //详情倒计时2
    spellTime2: function() {
        let that = this;
        let dates = that.data.spellingData;
        let len = dates.length;
        //时间数据长度
                function nowTime() {
            //时间函数
            for (var i = 0; i < len; i++) {
                var intDiff = dates[i].rest_time;
                //获取数据中的时间戳
                                var day = 0, hour = 0, minute = 0, second = 0;
                if (intDiff > 0) {
                    //转换时间
                    day = Math.floor(intDiff / (60 * 60 * 24));
                    hour = Math.floor(intDiff / (60 * 60)) - day * 24;
                    minute = Math.floor(intDiff / 60) - day * 24 * 60 - hour * 60;
                    second = Math.floor(intDiff) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60;
                    if (hour <= 9) hour = "0" + hour;
                    if (minute <= 9) minute = "0" + minute;
                    if (second <= 9) second = "0" + second;
                    dates[i].rest_time--;
                    var str = hour + ":" + minute + ":" + second;
                } else {
                    var str = "已结束！";
                    // clearInterval(timer);
                                }
                dates[i].difftime = str;
                //在数据中添加difftime参数名，把时间放进去
                        }
            that.setData({
                spellingData: dates
            });
        }
        nowTime();
        var timer = setInterval(nowTime, 1e3);
    },
    //详情倒计时3
    count_down: function() {
        let that = this;
        let times = that.data.userData.remaining_time;
        if (times < 0) {
            times = times + 24 * 3600;
        }
        // var timer = null;
                that.data.timer = setInterval(function() {
            var day = 0, hour = 0, minute = 0, second = 0;
            //时间默认值
                        if (times > 0) {
                hour = Math.floor(times / (60 * 60)) - day * 24;
                minute = Math.floor(times / 60) - day * 24 * 60 - hour * 60;
                second = Math.floor(times) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60;
            }
            if (hour <= 9) hour = "0" + hour;
            if (minute <= 9) minute = "0" + minute;
            if (second <= 9) second = "0" + second;
            that.setData({
                time: hour + ":" + minute + ":" + second
            });
            times--;
        }, 1e3);
        if (times <= 0) {
            clearInterval(that.data.timer);
        }
    },
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                that.setData({
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    on_off_trans_free: res.extra.on_off_trans_free,
                    trans_for_free_barrier: res.extra.trans_for_free_barrier,
                    new_member_audit: res.extra.new_member_audit,
                    userAuditStatus: res.extra.userAuditStatus ? res.extra.userAuditStatus : 2
                });
            }
        });
    },
    //获取tmplIds
    getTmplIds: function() {
        let that = this;
        const version = wx.getSystemInfoSync().SDKVersion;
        if (util.compareVersion(version, "2.8.2") < 0) {
            that.setData({
                tmplIds: [],
                subscribeMessage: false
            });
            return;
        }
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                let tmplIds = [];
                let subscribeMessage = true;
                res.extra.map(v => {
                    if ((v.type == "21" || v.type == "22" || v.type == "23") && v.status == "1") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage
                });
            }
        });
    }
});